layui.define(['index', 'sliderVerify'], function(exports) {
    const {$, form, setter, layer} = layui, router = layui.router(), search = router.search;
    const slider = layui.sliderVerify.render({
        elem: '#slider',
        onOk: function() {
            layer.msg("滑块验证通过");
        }
    }), account = AppGeneral.localStorage.getItem('REMEMBER_ACCOUNT');
    form.on('submit(LAY-user-login-submit)', function(obj) {
        if (!slider.isOk()) return layer.msg("请先通过滑块验证");
        const formData = {
            username: CryptoJS.enc.Utf8.parse(obj.field.username).toString(CryptoJS.enc.Base64),
            password: CryptoJS.enc.Utf8.parse(obj.field.password).toString(CryptoJS.enc.Base64)
        };
        layer.msg('正在请求...', { icon: 16, shade: 0.01, time: false });
        $.ajax({
            url: setter.request.apiUrl + '/login',
            type: "post",
            data: formData,
            success: function (result) {
                if (result.code !== 200) {
                    slider.reset();
                    return layer.msg('账号密码错误', {icon: 5});
                }
                if (!account && obj.field.remember) {
                    AppGeneral.localStorage.setItem("REMEMBER_ACCOUNT", formData, 86400);
                }else if (account && !obj.field.remember) {
                    localStorage.removeItem('REMEMBER_ACCOUNT');
                }
                const {token} = result.data;
                if (!token) {
                    slider.reset();
                    return layer.msg('系统错误：登录失败', {icon: 5});
                }
                return getSystemMenus(result.data);
            },
            error: function () {
                slider.reset();
                layer.msg("网络异常", {icon: 5});
            }
        })
    });

    async function getSystemMenus(lData) {
        const {token, expire, userInfo} = lData;
        await getConfig(token);
        $.ajax({
            url: setter.request.apiUrl + '/systemMenus',
            headers: {
                Authorization: setter.request.tokenType + token
            },
            success: function (result) {
                if (result.code !== 200) {
                    slider.reset();
                    return layer.msg('获取权限失败', {icon: 5});
                }
                const data = result.data, menus = data.menus || [];
                if (menus.length === 0) {
                    slider.reset();
                    return layer.msg('当前用户无任何菜单权限，请联系系统管理员', {icon: 5});
                }
                localStorage.setItem("MENUS", CryptoJS.enc.Utf8.parse(JSON.stringify(menus)).toString(CryptoJS.enc.Base64));
                localStorage.setItem("PERMISSIONS", CryptoJS.enc.Utf8.parse(JSON.stringify(data.permissions)).toString(CryptoJS.enc.Base64));
                localStorage.setItem("USERINFO", userInfo);
                AppGeneral.localStorage.setItem("TOKEN", token, expire);
                layer.msg('登录成功，正在跳转...', {icon: 6,time: 500}, function () {
                    return location.hash = search.redirect ? decodeURIComponent(search.redirect) : '/';
                });
            },
            error: function () {
                slider.reset();
                layer.msg('网络错误', {icon: 5});
            }
        });
    }
    function getConfig(token) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: setter.request.apiUrl + '/webSite',
                headers: {
                    Authorization: setter.request.tokenType + token
                },
                success: function(result) {
                    result.code === 200 && localStorage.setItem("WEBSITE", result.data);
                    resolve();
                },
                error: function () {
                    reject();
                }
            })
        })

    }
    if (account) {
        form.val('LAY-user-login-form', {
            username: CryptoJS.enc.Base64.parse(account.username).toString(CryptoJS.enc.Utf8),
            password: CryptoJS.enc.Base64.parse(account.password).toString(CryptoJS.enc.Utf8),
            remember: true,
        });
    }
    form.render(null, 'LAY-user-login-form');
    exports('login', {})
});
